﻿using Infrastructures;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConcreteService
{
    internal class ProcessHelper
    {
        internal static void ProcessAfterDone<T>(T obj, string oper, EventType eType, bool isSync = true)
        {
            CacheManager.Put(obj);
            if (isSync)
                LogEvent(obj, oper, eType);
            else
            {
                new Action(() =>
                {
                    LogEvent(obj, oper, eType);
                }).BeginInvoke(null, null);
            }
        }

        internal static void ProcessAfterDelete<T>(string code, T obj, string oper, EventType eType, bool isSync = true)
        {
            CacheManager.Delete<T>(code);

            if (isSync)
                LogEvent(obj, oper, eType);
            else
            {
                new Action(() =>
                {
                    LogEvent(obj, oper, eType);
                }).BeginInvoke(null, null);
            }
        }

        internal static void LogEvent<T>(T obj, string oper, EventType eType)
        {
            EventLog log = new EventLog();
            log.ActionType = eType;
            log.Remark = obj.ToString();
            log.Operator = oper;

            Type type = obj.GetType();
            log.ActionObject = type.Name;
            var attr = (CommonAttr)Attribute.GetCustomAttribute(type, typeof(CommonAttr));
            log.EventID = attr == null ? SystemConfig.Get("SysEventID") : type.GetProperty(attr.PrimaryKey).GetValue(obj) == null ? SystemConfig.Get("SysEventID") : type.GetProperty(attr.PrimaryKey).GetValue(obj).ToString();

            LogUtil.Create(log);
        }
    }
}
